<template>
  <div>
    <el-dialog
      :close-on-click-modal="false"
      :beforeClose="handleClose2"
      title="合并排货"
      :visible.sync="dialogVisible2"
      width="1200px">
      <div style="height:600px;overflow-y: auto">
        <el-form :model="sendForm" size="mini" label-width="120px"  ref="sendForm" :rules="rules2">
          <el-form-item label="客户名称：">
            {{sendForm.customerName}}
          </el-form-item>
          <el-form-item label="结算方式：">
            <span v-if="sendForm.orderRemark" :style="{color:(sendForm.orderRemark.indexOf('货到付款') != -1 || sendForm.orderRemark.indexOf('货到票到付款') != -1) ? 'red' : '#606266'}">{{sendForm.orderRemark}}</span>
          </el-form-item>
          <el-form-item label="提货时间："  prop="takeTime">
            <el-date-picker
              :picker-options="pickerOptions"
              value-format="yyyy-MM-dd"
              v-model="sendForm.takeTime"
              style="display: inline-block;width:150px"
              type="date"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="提货概率：" prop="isSure">
            <el-radio-group v-model="sendForm.isSure">
              <el-radio :label="1">确定<span style="color:#999;padding-left:5px">(保证准时发货)</span></el-radio>
              <el-radio :label="0">不确定</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="提货类型：" prop="planSendType">
            <el-radio-group v-model="sendForm.planSendType">
              <el-radio label="工厂发货">工厂发货</el-radio>
              <el-radio label="运联发货">运联发货</el-radio>
              <el-radio label="自提">自提</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="发同批次同产线" prop="isSameBatch">
            <el-radio-group v-model="sendForm.isSameBatch">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <div>
            <div class="th-item" v-for="(item,index) in sendForm.detailData">
              <div class="th-left">
                <div style="font-weight: bold;margin-bottom:10px;">{{ item.goodsName }} / {{item.goodsSn}}</div>
                <el-form-item label="发货类型" style="margin-bottom:0px;" label-width="80px">{{ item.sendType}}</el-form-item>
                <el-form-item label="合同数量" style="margin-bottom:0px;" label-width="80px">{{ item.goodsNum}}吨</el-form-item>
                <el-form-item label="已发货" style="margin-bottom:0px;" label-width="80px">{{ item.goodsSendNum}}吨</el-form-item>
                <el-form-item label="已安排" style="margin-bottom:0px;" label-width="80px">{{ item.goodsPlanNum}}吨</el-form-item>
                <el-form-item label="未安排" style="margin-bottom:0px;" label-width="80px">{{ item.goodsUnPlanNum}}吨</el-form-item>
                <el-form-item label="订单备注" style="margin-bottom:0px;" label-width="80px">{{ item.goodsRemark1}}</el-form-item>
                <el-form-item label="询盘备注" style="margin-bottom:0px;" label-width="80px">{{ item.freightRemark}}</el-form-item>
              </div>
              <div class="th-right">
                <el-form-item label="提货数量" :prop="`detailData.${index}.planNum`" :rules="rules2.planNum">
                  <el-input style="width:80px;" v-model="item.planNum"></el-input><span style="padding-left:5px">吨</span>
                </el-form-item>
                <el-form-item label="商品包装" :prop="`detailData.${index}.goodsWeight`" :rules="rules2.goodsWeight">
                  <el-input style="width:80px" v-model="item.goodsWeight"></el-input><span style="padding-left:5px">kg/包</span>
                  <span style="padding-left:20px;"> <el-checkbox v-model="item.isHasTray">带托</el-checkbox></span>
                </el-form-item>
                <el-form-item label="商品备注" >
                  <el-input  v-model="item.goodsRemark"></el-input>
                </el-form-item>
                <el-form-item label="关联类型" :prop="`detailData.${index}.relationOrderType`" :rules="rules2.relationOrderType">
                  <el-radio-group v-model="item.relationOrderType" @change="changeRelationOrderType(index)">
                    <el-radio label="purchaseOrder">采购合同</el-radio>
                    <el-radio label="agentProcess">代加工单</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="关联单号" :prop="`detailData.${index}.relationDetailIds`" :rules="rules2.relationDetailIds">
                  <el-select v-model="item.relationDetailIds" clearable style="width:100%" filterable placeholder="请输入关键词" multiple>
                    <el-option
                      :class="{'zdt-opt2':ii.isShow ==1 && item.relationOrderType == 'purchaseOrder'}"
                      :value="ii.detailId" :label="ii.purchaseSn+'/'+ii.goodsSn+'/'+ii.goodsNum+'吨/'+'￥'+ii.goodsPrice+'/可提'+ii.unTakeNum+'吨'+'/'+ii.supplierName" v-for="ii in purchaseOrderArray[index]" :key="ii.detailId"></el-option>
                  </el-select>
                </el-form-item>
              </div>
            </div>
          </div>


          <div v-if="sendForm.planSendType != '工厂发货'">
            <el-form-item label="仓库：" prop="takeWarehouse">
              <el-select
                style="width:250px;display: inline-block"
                clearable
                v-model="sendForm.takeWarehouse"
                filterable
                remote
                reserve-keyword
                placeholder="请输入关键词"
                @change="changeWarehouseId"
                :remote-method="remoteMethod2"
                :loading="loading">
                <el-option
                  v-for="item in options2"
                  :key="item.warehouseId"
                  :label="item.warehouseName+' / '+item.warehouseAddress"
                  :value="item.warehouseName">
                </el-option>
              </el-select>
              <el-button type="text" style="display: inline-block" @click="showDialog5">增加仓库</el-button>
            </el-form-item>
            <el-form-item label="联系人："  prop="contactName" >
              <el-input v-model="sendForm.contactName"  style="width:200px"></el-input>
            </el-form-item>
            <el-form-item label="手机号："  prop="contactMobile">
              <el-input v-model="sendForm.contactMobile" style="width:200px"></el-input>
            </el-form-item>
            <el-form-item label="提货地点："  prop="takeAddress">
              <el-input v-model="sendForm.takeAddress" style="width:80%" :autosize="{ minRows: 2, maxRows: 6}" type="textarea"></el-input>
            </el-form-item>
            <el-form-item label="注意事项：" >
              <el-input :autosize="{ minRows: 2, maxRows: 6}" type="textarea" v-model="sendForm.takeNote" style="width:80%"></el-input>
            </el-form-item>
            <el-form-item label="提货备注：" >
              <el-input :autosize="{ minRows: 2, maxRows: 6}" type="textarea" v-model="sendForm.takeRemark" style="width:80%"></el-input>
            </el-form-item>
            <el-form-item label="司机卸货：" v-if="sendForm.planSendType == '运联发货'">
              <el-radio-group v-model="sendForm.isNeedDriverUnload">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <div v-if="sendForm.planSendType == '自提'">
              <el-form-item label="车牌号："  prop="driverTruckNo">
                <el-input  style="width:200px" v-model="sendForm.driverTruckNo"></el-input>
              </el-form-item>
              <el-form-item label="司机姓名：" prop="driverName">
                <el-input  style="width:200px" v-model="sendForm.driverName"></el-input>
              </el-form-item>
              <el-form-item label="手机号：" prop="driverMobile">
                <el-input style="width:200px" v-model="sendForm.driverMobile"></el-input>
              </el-form-item>
              <el-form-item label="身份证：" >
                <el-input style="width:200px" v-model="sendForm.driverIdNumber"></el-input>
              </el-form-item>
            </div>
          </div>

        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose2">取 消</el-button>
          <el-button type="primary" @click="handleConfirm2" :loading="btnLoading2">确 定</el-button>
      </span>
    </el-dialog>

    <!--增加仓库-->
    <warehouseInfo ref="warehouseInfo" @getList="getWarehouseList"></warehouseInfo>

  </div>
</template>
<script>
import "@/utils/jQuery.print"
import {getPlanList,goodsList,getUnPlanList,warehouseList,getWarehouseDetail,postPlanGoods,warehouseAdd,getPlanGoodsList,getGoodsPlanList,changePlanDate,cancelGoodsPlan,selfTakeInfo,ordGoodsFilter,planGoodsFilter} from '@/api/company'
import warehouseInfo from "./warehouseInfo.vue"
import {orderGoodsDetailPlan,needTakePurchaseGoods,warehouseListPlan,planOrderGoods,checkPlanOrderIsPaid} from '@/api/order'


const defaultSendForm={
  "takeTime" : "", //提货时间
  "isSure" : 1, //提货概率(0不确定，1确定)
  "planSendType" : "工厂发货",  //提货类型:工厂发货、运联发货、自提
  "detailData" : [],  //排货的商品信息
  "takeWarehouse" : "" ,//提货仓库
  "contactName" : "", //联系人
  "contactMobile" : "", //联系人手机号
  "takeAddress" : "",  //提货地址
  "takeRemark" : "原厂正牌，原料生产日期不超过合同签订日前六个月，外观无破损、潮湿，无大面积污渍，包装袋规格及颜色一致。", //提货备注
  "takeNote" : "", //注意事项
  "driverName" : "", //司机姓名
  "driverMobile" : "", //司机手机号
  "driverTruckNo" : "", //司机车牌号
  "isNeedDriverUnload" : '', //是否需要司机卸货(0不需要，1需要)
  driverIdNumber:'',
  isSameBatch:'',//是否同批次
};
export default {
  name: "printdischarging",
  data(){
    const isvalidatePurchaseOrderId = (rule, value, callback) => {
      console.log("rule",rule)
      let indexArray = rule.field.split(".")
      let index = indexArray[1] ? indexArray[1] : -1
      let cutgoodsSn = this.sendForm.detailData[index] ? this.sendForm.detailData[index]['goodsSn'] : ''
      if(this.sendForm.planSendType == '工厂发货' && value.length == 0&&cutgoodsSn.indexOf('备注型号')==-1 ){
        callback(new Error('请关联单号'))
      }else if(this.sendForm.planSendType == '运联发货' && this.curWarehouse.isSelfBusiness==0 && value.length == 0&&cutgoodsSn.indexOf('备注型号')==-1 ){
        callback(new Error('请关联单号'))
      } else if(this.sendForm.planSendType == '自提' && this.curWarehouse.isSelfBusiness==0 && value.length == 0&&cutgoodsSn.indexOf('备注型号')==-1 ){
        callback(new Error('请关联单号'))
      } else {
        callback()
      }
    };
    return {
      dialogVisible2:false,
      rules2:{
        takeTime      : [{required: true, message: '请输入提货时间', trigger: 'blur'},],
        isSure:[{required: true, message: '请选择提货概率', trigger: 'change'},],
        planNum       : [{required: true, message: '请输入提货数量', trigger: 'blur'},],
        goodsWeight: [{required: true, message: '请输入商品包装', trigger: 'blur'},],
        relationOrderType: [{required: true, message: '请选择关联类型', trigger: 'change'},],
        relationDetailIds: [{required: true, validator: isvalidatePurchaseOrderId, trigger: 'change'},],
        takeWarehouse   :[{required: true, message: '请选择仓库', trigger: 'change'},],
        contactName   : [{required: true, message: '请输入联系人', trigger: 'blur'},],
        contactMobile : [{required: true, message: '请输入联系人手机号', trigger: 'blur'},],
        takeAddress   : [{required: true, message: '请输入提货地址', trigger: 'blur'},],
        planSendType      : [{required: true, message: '请选择提货类型', trigger: 'change'},],
        driverTruckNo: [{required: true, message: '此项必填', trigger: 'blur'},],
        driverName: [{required: true, message: '此项必填', trigger: 'blur'},],
        driverMobile: [{required: true, message: '此项必填', trigger: 'blur'},],
        isSameBatch:[{required: true, message: '此项必填', trigger: 'change'},],
      },
      btnLoading2:false,
      sendForm: JSON.parse(JSON.stringify(defaultSendForm)),

      options2:[],
      goodsPlanList:[],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7
        }
      },

      cutItem:{},
      purchaseOrderList:[],
      curWarehouse:{},
      listLoading:false,
      loading:false,
      purchaseOrderArray:[]
    }
  },

  components : {
    warehouseInfo:warehouseInfo
  },

  filters:{

  },

  created() {

  },

  methods:{
    //获取指定合同排货列表
    getGoodsPlanListData(ogId){
      getGoodsPlanList({ogId:ogId}).then((res)=>{
        this.goodsPlanList = res
      })
    },

    //显示增加仓库弹窗
    showDialog5(){
      this.$refs.warehouseInfo.showDialog('add',null);
    },
    //仓库列表
    getWarehouseList(keywords,warehouseId){
      warehouseListPlan({keywords:keywords}).then((res)=>{
        this.options2 = res;
        console.log(keywords)
        if(warehouseId){
          this.changeWarehouseId(keywords);
          this.sendForm.takeWarehouse = keywords
        }
        this.btnLoading5 = false;
      })
    },
    //搜索仓库
    remoteMethod2(query) {
      if (query !== '') {
        this.loading2 = true;
        warehouseListPlan({keywords:query}).then((res)=>{
          this.options2 = res;
          this.loading2 = false;
        })
      } else {
        this.options = [];
        this.loading2 = false;
      }
    },

    changeWarehouseId(val){
      let curWarehouse = this.options2.find((el)=>{
        return el.warehouseName == val
      });
      console.log("curWarehouse",curWarehouse)
      this.curWarehouse = JSON.parse(JSON.stringify(curWarehouse));
      if(curWarehouse.warehouseId){
        // getWarehouseDetail({warehouseId:curWarehouse.warehouseId}).then((res)=>{
          this.sendForm.contactName  = this.curWarehouse.contactName;
          this.sendForm.contactMobile = this.curWarehouse.contactMobile;
          this.sendForm.takeAddress = this.curWarehouse.warehouseAddress;
          this.sendForm.takeNote = this.curWarehouse.takeNote;
        // });
      }else{
        this.sendForm = JSON.parse(JSON.stringify(defaultSendForm));
      }
    },

    //显示安排提货
    showDialog2(list){
      this.dialogVisible2 = true;
      let ogIds = [];
      list.forEach((el)=>{
        ogIds.push(el.ogId)
      })
      orderGoodsDetailPlan({ogIds:ogIds.join(",")}).then((res)=>{
        this.sendForm = JSON.parse(JSON.stringify(defaultSendForm))
        this.sendForm.customerName = res.customerName;
        this.sendForm.orderRemark = res.orderRemark;
        this.sendForm.userRealName = res.userRealName;
        this.sendForm.isSameBatch = res.isSameBatch
        this.sendForm.detailData = [];
        this.purchaseOrderArray = [];
        res.detailList.forEach(()=>{
          this.purchaseOrderArray.push([]);
        })
        res.detailList.forEach((el,index)=>{
          this.sendForm.detailData.push({
            detailId:el.detailId,
            goodsKingId:el.goodsKingId,
            goodsName : el.goodsName, //商品名称
            goodsSn   : el.goodsSn, //商品牌号
            unSendNum : el.unSendNum, //未发货数量
            goodsPlanNum : el.goodsPlanNum, //已安排数量
            goodsUnPlanNum : el.goodsUnPlanNum, //未安排数量
            goodsSendNum : el.goodsSendNum, //已发货数量
            goodsNum : el.goodsNum, //合同数量
            sendType :  el.sendType, //发货类型
            expectSendDate : el.expectSendDate, //期望发货时间
            warehouseName : el.warehouseName, //预计发货仓库
            goodsRemark1 : el.goodsRemark, //备注
            planNum   : el.goodsUnPlanNum, //提货数量
            relationOrderType : "purchaseOrder", //关联的订单类型(采购单-purchaseOrder,代加工单-agentProcess)
            relationDetailIds : [], //关联的订单ID
            goodsWeight : '', //包装重量
            isHasTray : false,
            goodsRemark : '',
            freightRemark:el.freightRemark

          })
          this.remoteMethod(el.goodsKingId,'purchaseOrder',index,el.orderId)
        })
      })
    },

    //获取关联采购单
    remoteMethod(goodsKingId,relationOrderType,index,orderId){
       return needTakePurchaseGoods({goodsKingId:goodsKingId,orderId:orderId,orderType:relationOrderType}).then((res)=>{
          this.purchaseOrderArray.splice(index,1,res)
      })
    },

    //切换关联类型
    changeRelationOrderType(index){
       let c = JSON.parse(JSON.stringify(this.sendForm.detailData[index]));
       c.relationDetailIds = [];
       console.log("c",c)
       this.remoteMethod(c.goodsKingId,c.relationOrderType,index);
    },

    //关闭安排提货
    handleClose2(){
      this.dialogVisible2 = false;
      this.$refs.sendForm.clearValidate();
    },

    //提交安排提货
    handleConfirm2(){
      this.$refs['sendForm'].validate((valid) => {
        if (valid) {
          let pa = JSON.parse(JSON.stringify(this.sendForm));
          pa.isNeedDriverUnload = pa.isNeedDriverUnload ? 1 : 0;
          if(pa.planSendType == '工厂发货'){
            pa.takeWarehouse = '';
            pa.contactName = '';
            pa.contactMobile = '';
            pa.takeAddress = '';
            pa.takeRemark = '';
            pa.takeNote = '';
            pa.isNeedDriverUnload = 0;
            pa.driverName = '';
            pa.driverMobile = '';
            pa.driverTruckNo = '';
            pa.driverIdNumber = '';
          }else if(pa.planSendType == '运联发货'){
              pa.driverName = '';
              pa.driverMobile = '';
              pa.driverTruckNo = '';
              pa.driverIdNumber = '';
          }else if(pa.planSendType == '自提'){
              pa.isNeedDriverUnload = 0;
          }
          pa.detailData = [];
          this.sendForm.detailData.forEach((el)=>{
            pa.detailData.push({
              detailId  : el.detailId,
              planNum   : el.planNum, //提货数量
              relationOrderType : el.relationOrderType, //关联的订单类型(采购单-purchaseOrder,代加工单-agentProcess)
              relationDetailIds : el.relationDetailIds, //关联的订单ID
              goodsWeight : el.goodsWeight, //包装重量
              isHasTray : el.isHasTray ? 1 : 0, //是否含托(1是，0否)
              goodsRemark:el.goodsRemark
            })
          })
          this.isPopConfirm(pa)
        }
      })
    },


    //排货提示判断
    isPopConfirm(data){
      console.log("data",data);
      let pa = {};
      pa.detailData = JSON.parse(JSON.stringify(data.detailData))
      checkPlanOrderIsPaid(pa).then((res)=> {
        let msg = ''
        if (res.isHasUnPaidAmount == 1 && res.isNotEnoughPaidAmount == 1) {
          msg = '排货客户存在未结清的历史订单并且排货客户订单付款金额不足，请确认是否排货？'
        } else if (res.isHasUnPaidAmount == 1) {
          msg = '排货客户存在未结清的历史订单，请确认是否排货？'
        } else if (res.isNotEnoughPaidAmount == 1) {
          msg = '排货客户订单付款金额不足，请确认是否排货？'
        }
        if (msg != '') {
          this.$confirm(msg, '提示', {
            confirmButtonText: '继续排货',
            cancelButtonText: '取消排货',
            type: 'warning'
          }).then(() => {
            this.btnLoading2 = true;
            this.pushPH(data)
          }).catch(() => {
            // this.btnLoading2 = false;
            this.dialogVisible2 = false;
          })
        } else {
          this.btnLoading2 = true;
          this.pushPH(data)
        }
      })
    },

    //提交排货
    pushPH(pa){
      planOrderGoods(pa).then((res)=>{
        this.btnLoading2 = false;
        this.dialogVisible2 = false;
        if(res.isPurchaseHasUnPaid == 1){
          this.$message({
            message: '当前关联采购合同未付款，请尽快安排付款',
            type: 'warning'
          });
        }
        this.$emit('handleConfirmMerge')
      }).catch(()=>{
        this.btnLoading2 = false;
      })
    }

  },
}
</script>

<style scoped lang="scss">
.zdt-opt2{
  color:red
}
      .th-item{
        display: flex;
        margin-top: 20px;
        border: 1px solid #eee;
        padding: 16px;
        justify-items: flex-start;
        align-items: flex-start;
        .th-left{
          border-right: 1px solid #eee;
          padding-right:20px;
          width:200px;
        }
        .th-right{
          width:calc(100% - 200px);
          padding-right:20px;
        }
      }
      .th-item:last-child{
        margin-bottom:20px;
      }
</style>
